package com.zhiwei.codesecurity.service.teams;

import com.zhiwei.codesecurity.common.base.NullObjectResp;
import com.zhiwei.codesecurity.common.base.ServiceResponse;
import com.zhiwei.codesecurity.common.enums.UserAndTeamType;
import com.zhiwei.codesecurity.common.utils.ServiceResponseUtil;
import com.zhiwei.codesecurity.common.utils.StringUtils;
import com.zhiwei.codesecurity.entity.Teams;
import com.zhiwei.codesecurity.entity.Users;
import com.zhiwei.codesecurity.mapper.TeamsDao;
import com.zhiwei.codesecurity.mapper.TeamsMapper;
import com.zhiwei.codesecurity.mapper.UsersMapper;
import com.zhiwei.codesecurity.service.teams.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("teamService")
public class TeamServiceImpl implements ITeamService {
    private final static Logger logger = LoggerFactory.getLogger(TeamServiceImpl.class);

    @Autowired
    private TeamsDao teamsDao;

    @Autowired
    private TeamsMapper teamsMapper;

    @Autowired
    private UsersMapper usersMapper;

    /**
     * 根据团队ID查询团队信息
     * @param teamId
     * @return
     */
    public ServiceResponse<Teams> queryTeam(String teamId) {
        logger.info(">>>>>> queryTeam start ... ");
        if (StringUtils.isBlank(teamId)) {
            logger.error("=== 请求参数为空|teamId= {}", teamId);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        Teams teams = teamsDao.getByPrimaryKey(teamId);
        if (null == teams) {
            logger.error("=======查询团队失败|teamId= {}", teamId);
            return ServiceResponseUtil.createServiceResponseForBisError("查询团队失败!");
        }

        return ServiceResponseUtil.createServiceResponse(teams);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<AddTeamServRlt> addTeam(Teams teams) {
        logger.info(">>>>>> addTeam start ... ");
        // 请求参数验证
        if (null == teams) {
            logger.error("=== 请求参数为空|users= {}", teams);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        if (0 == teamsDao.add(teams)) {
            logger.error("=======添加团队失败========");
            return ServiceResponseUtil.createServiceResponseForBisError("添加团队失败!");
        }

        AddTeamServRlt addUserServRlt = new AddTeamServRlt();
        addUserServRlt.setTeamId(teams.getId());
        return ServiceResponseUtil.createServiceResponse(addUserServRlt);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<NullObjectResp> modifyTeam(Teams teams) {
        logger.info(">>>>>> modifyTeam start ... ");
        // 请求参数验证
        if (null == teams) {
            logger.error("=== 请求参数为空|users= {}", teams);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        Teams teamsNew = teamsDao.getByPrimaryKey(teams.getId());
        if (null == teamsNew) {
            logger.warn("=== 修改团队不存在|userId={}", teams.getId());
            return ServiceResponseUtil.createServiceResponseForParamError("修改团队不存在!");
        }

        teamsNew.setTeamName(teams.getTeamName());
        teamsNew.setUpdateTime(new Date());
        teamsNew.setDataVersion(teamsNew.getDataVersion() + 1);
        if (0 == teamsDao.update(teamsNew)) {
            logger.warn("=== 修改用户失败|userId={}", teamsNew.getId());
            return ServiceResponseUtil.createServiceResponseForParamError("修改团队失败!");
        }
        return ServiceResponseUtil.createServiceResponse();
    }

    public ServiceResponse<QueryTeamAndUserServListRlt> queryTeamAndUserByTeamId(String teamId) {
        logger.info(">>>>>> queryTeamAndUserByTeamId start ... ");
        // 请求参数验证
        if (StringUtils.isBlank(teamId)) {
            logger.error("====请求参数为空|teamId= {}", teamId);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        List<QueryTeamAndUserServRlt> queryTeamAndUserServRltList = new ArrayList<>();

        Teams teams = teamsDao.getByPrimaryKey(teamId);
        if (null == teams) {
            logger.error("====查询的根节点不存在!|teamId= {}", teamId);
            return ServiceResponseUtil.createServiceResponseForParamError("查询的根节点不存在!");
        }

        queryTeamAndUserServRltList = initTeamAndUserServRlt(teamId, queryTeamAndUserServRltList);

        QueryTeamAndUserServListRlt queryTeamAndUserServListRlt = new QueryTeamAndUserServListRlt();
        queryTeamAndUserServListRlt.setDatas(queryTeamAndUserServRltList);


        return ServiceResponseUtil.createServiceResponse(queryTeamAndUserServListRlt);
    }

    private List<QueryTeamAndUserServRlt> initTeamAndUserServRlt(String teamId,
                                                                  List<QueryTeamAndUserServRlt> queryTeamAndUserServRltList) {
        List<Teams> teamsList = teamsMapper.getTeamsByParentTeamId(teamId);
        if (teamsList != null && teamsList.size() > 0) {
            QueryTeamAndUserServRlt teamServRlt;
            for (Teams teams : teamsList) {
                teamServRlt = new QueryTeamAndUserServRlt();
                teamServRlt.setTeamOrUserId(String.valueOf(teams.getId()));
                teamServRlt.setTeamOrUserName(teams.getTeamName());
                teamServRlt.setType(String.valueOf(UserAndTeamType.TEAM.getKey()));
                queryTeamAndUserServRltList.add(teamServRlt);
            }
        }

        List<Users> usersList = usersMapper.getUsersByTeamId(teamId);
        if (usersList != null && usersList.size() > 0) {
            QueryTeamAndUserServRlt userServRlt;
            for (Users users : usersList) {
                userServRlt = new QueryTeamAndUserServRlt();
                userServRlt.setTeamOrUserId(users.getUserId());
                userServRlt.setTeamOrUserName(users.getUserName());
                userServRlt.setType(String.valueOf(UserAndTeamType.USER.getKey()));
                queryTeamAndUserServRltList.add(userServRlt);
            }
        }

        return queryTeamAndUserServRltList;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public ServiceResponse<NullObjectResp> deleteTeam(String teamId) {
        logger.info(">>>>>> deleteTeam start ... ");
        if (StringUtils.isBlank(teamId)) {
            logger.error("=== 请求参数为空|teamId= {}", teamId);
            return ServiceResponseUtil.createServiceResponseForParamError("请求参数为空!");
        }

        // 删除团队下面的用户（逻辑删除）
        usersMapper.delByTeamId(teamId);
        // 删除该团队
        teamsMapper.delByTeamId(teamId);

        return ServiceResponseUtil.createServiceResponse();
    }
}
